package com.gopay.common.security.signUtil;

import com.gopay.common.constants.Constants;
import com.gopay.common.constants.proccode.ProcCodeEnum;
import com.gopay.common.exception.GopayException;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;

/**
 * 加密签名工具类.
 * 
 * @SignUtil.java
 * @author GongZhong
 * @2012-12-25 下午04:31:28 www.gopay.com.cn Inc.All rights reserved.
 */
public abstract class SignUtil {

    /**
     * 对信息按照stype所要求进行加密
     * 
     * @param message
     * @param type
     * @return
     * @throws GopayException
     */
    public static final String sign(String message, String type) throws GopayException {
        // 1:MD5,2:SHA,3:API证书
        if (Constants.SIGN_SHA.equals(type)) {
            return sha(message);
        } else if(Constants.SIGN_MD5.equals(type)){
            return md5(message);
        } else if(Constants.SIGN_API.equals(type)){
            //服务器签名传参数较多放在操作放在个子的业务逻辑里面判断
            return "";
        }else{
            return md5(message);
        }
    }

    private static String md5(String message) throws GopayException {
        try {
            return DigestUtils.md5Hex(message.getBytes(Constants.ENCODE_UTF8));
        } catch (UnsupportedEncodingException e) {
            throw new GopayException(ProcCodeEnum.PROC_CODE_100E1002);
        }
    }

    private static String sha(String message) throws GopayException {
        try {
            return DigestUtils.shaHex(message.getBytes(Constants.ENCODE_UTF8));
        } catch (UnsupportedEncodingException e) {
            throw new GopayException(ProcCodeEnum.PROC_CODE_100E1002);
        }
    }
}
